package project.innovation.mooddiagnosis.server;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.python.antlr.ast.Str;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import project.innovation.mooddiagnosis.dao.MessageMapper;
import project.innovation.mooddiagnosis.entity.message.MessageInfo;
import project.innovation.mooddiagnosis.util.MindChat;
import project.innovation.mooddiagnosis.vo.ChatRequestParameter;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

@Component
@ServerEndpoint("/chatWebSocket/{userId}")
@Service
@Slf4j
public class ChatWebSocketServer {
    /**
     * 当前在线链接数
     */
    private static int onlineCount = 0;

    /**
     * 存放每个用户对应的ChatWebSocketServer对象
     */
    private static ConcurrentHashMap<String, ChatWebSocketServer> sessionHashMap = new ConcurrentHashMap<String, ChatWebSocketServer>();
//奇妙的static关键字
    /**
     * （特定的）用户的链接会话
     */
    private Session session;

    private String userId;

    private ObjectMapper mapper = new ObjectMapper();
    private static MindChat mindChat = new MindChat();
    private static MessageMapper messageMapper = new MessageMapper() {
        @Override
        public Integer insertMessage(MessageInfo message) {
            return 0;
        }

        @Override
        public List<MessageInfo> selectMessageOrderByMessageId(String userId) {
            return List.of();
        }

        @Override
        public Integer updateMessage(MessageInfo message) {
            return 0;
        }
    };

    @Autowired
    public void setMindChat(MindChat mindChat) {
        ChatWebSocketServer.mindChat = mindChat;
    }

    @Autowired
    public void setMessageMapper(MessageMapper messageMapper) {
        ChatWebSocketServer.messageMapper = messageMapper;
    }

    private ChatRequestParameter chatRequestParameter = new ChatRequestParameter();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        log.info("onOpen userId {}", userId);
        this.session = session;
        this.userId = userId;
        sessionHashMap.put(userId, this);
        onlineCount++;
    }

    @OnClose
    public void onClose() {
        log.info("onClose userId {}", userId);
        sessionHashMap.remove(userId);
        onlineCount--;
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException, InterruptedException {
        log.info("onMessage userId {}, message {}", userId, message);
        chatRequestParameter.setDiag(message);
        mindChat.sendMessage(userId, chatRequestParameter);
        CompletableFuture.runAsync(() -> {
            String response = null;
            try {
                response = mindChat.getAnswer(userId);
                log.info("userId{} , response: {}", userId, response);
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setMessage(message);
                messageInfo.setUserId(userId);
                messageInfo.setResponse(response);
                messageMapper.insertMessage(messageInfo);

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            try {
                session.getAsyncRemote().sendText(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
